package com.house.interceptors;

import com.house.context.RequestContextKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginInterceptor
 * @Description 登录拦截器
 * @Version 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    // 请求进入Controller前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        // token
        String token = request.getHeader("token");
        // 从redis中取数据
        if (!StringUtils.isEmpty(token)) { // 不为空
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null) { // 没有过期
                // 刷新redis过期时间
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES);

                // 放行
                return true;
            }
        }
        // 过期了{"success":false, "msg":"noLogin"}

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();

        return false;
    }

    //Controller的方法调用之后执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handle, ModelAndView modelAndView) throws Exception {
        //System.out.println("postHandle被调用");
    }

    //在请求处理后
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handle, Exception e) throws Exception {
        //在请求处理后调用
        if (handle instanceof HandlerMethod) {
            RequestContextKit.end();
        }
    }
}
